﻿using log4net;
using Mangox.BLL.Stock;
using Mangox.Common;
using Mangox.Model.MyBusinessDB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Configuration;
using System.Web.SessionState;

namespace MGXAPI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static bool isDebug = Convert.ToBoolean(Convert.ToInt32(ConfigurationManager.AppSettings["IsDebug"]));

/// <summary>
/// 预编译，web不适合使用，正式也可能用debug编译
/// </summary>
//#if DEBUG
//        public static bool isDebug = true;
//#else
//        public static bool isDebug = false;
//#endif


        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";       //获取类名 
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //默认输出json格式，去掉xml格式
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            InitData();
        }

        /// <summary>
        /// 开启webapi session
        /// https://blog.csdn.net/u012521795/article/details/79358907
        /// </summary>
        public override void Init()
        {
            this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            base.Init();
        }

        private void InitData()
        {
            //数据缓存
        }

        /// <summary>
        /// 默认首页，定位到路由index.html
        /// 需要对方法配置路由匹配
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //if (Context.Request.FilePath == "/") Context.RewritePath("index.html");
            if (Context.Request.FilePath == "/") Context.RewritePath("home/index");
        }


        //尽管我们在Global.asax的Application_Error方法中使用了Response.Redirect方法做页面重定向，但是当系统发生错误时Asp.Net认为错误没有被处理，所以最后页面还是会被重定向到Asp.Net的默认错误黄页，而不会跳转到我们在Application_Error方法中用Response.Redirect指向的页面。
        //404页面处理，404异常页面
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
            {
                Response.Redirect("/news/notfound.html");
            }
        }
    }
}
